package com.burgeon.backend.EnterpriseWeChat.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.burgeon.backend.EnterpriseWeChat.service.EWInfoService;
import com.burgeon.backend.SHOPBACKEND.service.ex.ErrorDataException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QYCode {
    private final static Log logger = LogFactory.getLog(QYCode.class);
    private static String CONTACT_ME="https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_contact_way?access_token=ACCESS_TOKEN";
    private static String GET_DATA="https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_contact_way?access_token=ACCESS_TOKEN";
    private static String DELETE_DATA="https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_contact_way?access_token=ACCESS_TOKEN";

    @Autowired
    private EWInfoService ewInfoService;


    public JSONObject updateNews(List empNo, String token, String accessToken) throws UnsupportedEncodingException {
//        String accessToken = ewInfoService.getAppAccessToken(token);
        JSONObject data = new JSONObject();
        data.put("type", "1");//单人
        data.put("scene", "2");//二维码
//        data.put("style","2");//咨询我
        data.put("user",empNo);//咨询我
        JSONObject res = null;
            res = doPostStr(CONTACT_ME.replace("ACCESS_TOKEN", accessToken), data.toJSONString());

        System.err.println(res);

        return res;

    }
    public JSONObject deleteContact(String configId, String accessToken) throws UnsupportedEncodingException {
//        String accessToken = ewInfoService.getAppAccessToken(token);
        JSONObject data = new JSONObject();
        data.put("config_id",configId );//单人
        JSONObject res = null;
        res = doPostStr(DELETE_DATA.replace("ACCESS_TOKEN", accessToken), data.toJSONString());

        System.err.println(res);

        return res;

    }



    /**
     * POST请求 - JSON格式数据
     * @param url
     * @param outStr
     * @return
     */
    public JSONObject doPostStr(String url, String outStr) throws UnsupportedEncodingException {
        System.err.println(outStr);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json;charset=UTF-8");// 解决请求乱码问题
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForEntity(url, new HttpEntity<String>(outStr, headers), String.class)
                .getBody();
        String json = new String(response.getBytes("ISO-8859-1"), "UTF-8");
        return JSON.parseObject(json);
    }

    public String contactMeCode(String empNo, String accessToken,String lfwd) throws ErrorDataException {
        System.err.println("empNo="+empNo);
        System.err.println("*****************************");
        RestTemplate rest = new RestTemplate();
        InputStream inputStream = null;
        OutputStream outputStream = null;
//        String sceneStr="id="+id+"&"+"token="+account;
        try {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_contact_way?access_token="+accessToken;
            Map<String,Object> param = new HashMap<>();
            param.put("type", "1");//单人
            param.put("scene", "2");//二维码
            param.put("style","2");//咨询我

            logger.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            logger.info("调用小程序生成微信永久小程序码URL接口返回结果:" + Arrays.toString(entity.getBody()));
            byte[] result = entity.getBody();

            inputStream = new ByteArrayInputStream(result);

            // 上传后的路径code
            String filePath = "D:/code/img/" + "QYContactMeCode/" + lfwd +"/" + empNo + ".png";
            File file = new File(filePath);
            if (!file.exists()){
                file.getParentFile().mkdirs();
            }
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();//http://lfwd.cloudsmicro.com

            return "http://lfwd.cloudsmicro.com/img/" + "QYContactMeCode/" + lfwd +"/" + empNo + ".png";
        } catch (Exception e) {
            logger.error("调用小程序生成微信永久小程序码URL接口异常",e);
            throw new ErrorDataException("调用小程序生成微信永久小程序码URL接口异常");
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
